#include "stdafx.h"
#include "clrchain.h"
using namespace System;

namespace $RootNamespace$
{

	int $CLRRequest$::Target::get()
	{
		return safe_cast<int>(_data);
	}

	$CLRRequest$::$CLRRequest$(System::Object ^data)
	{
		_data = data;
	}

	void $CLRHandler$::Test()
	{
		// Setup Chain of Responsibility 
		$CLRHandler$ ^h1 = gcnew $CLRConcreteHandlerA$();
		$CLRHandler$ ^h2 = gcnew $CLRConcreteHandlerB$();
		$CLRHandler$ ^h3 = gcnew $CLRConcreteHandlerC$();
		h1->SetSuccessor(h2);
		h2->SetSuccessor(h3);
		//Generate  requests
		array<$CLRRequest$^> ^reqsts = { gcnew $CLRRequest$(1), gcnew $CLRRequest$(7), gcnew $CLRRequest$(15), gcnew $CLRRequest$(23), gcnew $CLRRequest$(13), gcnew $CLRRequest$(6), gcnew $CLRRequest$(28), gcnew $CLRRequest$(23) };
		 //process requests
		for each ($CLRRequest$ ^request in reqsts)
		{
			h1->HandleRequest(request);
		}
	}

	void $CLRHandler$::SetSuccessor($CLRHandler$ ^successor)
	{
		this->successor = successor;
	}

	bool $CLRConcreteHandlerA$::CanHandle($CLRRequest$^ request)
	{
		return request->Target >= 0 && request->Target < 10;
	}

	void $CLRConcreteHandlerA$::HandleRequest($CLRRequest$ ^request)
	{
		if (request->Target >= 0 && request->Target < 10)
		{
			Console::WriteLine("{0} handled request {1}", this->GetType()->Name, request->Target);
	
		}
		else if (successor != nullptr)
		{
			successor->HandleRequest(request);
		}
	}

	bool $CLRConcreteHandlerB$::CanHandle($CLRRequest$^ request)
	{
		return request->Target >= 10 && request->Target < 20;
	}

	void $CLRConcreteHandlerB$::HandleRequest($CLRRequest$ ^request)
	{
		if (request->Target >= 10 && request->Target < 20)
		{
			Console::WriteLine("{0} handled request {1}", this->GetType()->Name, request->Target);
	
		}
		else if (successor != nullptr)
		{
			successor->HandleRequest(request);
		}
	}

	bool $CLRConcreteHandlerC$::CanHandle($CLRRequest$^ request)
	{
		return request->Target >= 20 && request->Target < 30;
	}

	void $CLRConcreteHandlerC$::HandleRequest($CLRRequest$ ^request)
	{
		if (request->Target >= 20 && request->Target < 30)
		{
			Console::WriteLine("{0} handled request {1}", this->GetType()->Name, request->Target);
	
		}
		else if (successor != nullptr)
		{
			successor->HandleRequest(request);
		}
	}

}
